package com.leboncoin.xml;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import com.leboncoin.bean.SearchItemBean;
import com.leboncoin.bean.SubscriptionBean;
import java.util.logging.Level;

public class ConfigManager {
	
	static final Logger logger = Logger.getLogger(ConfigManager.class.getName());	
	Document configuration;
	List<SubscriptionBean> subscriptions = null;
	
	
	public ConfigManager(String fileName) throws IOException, SAXException, ParserConfigurationException {
		super();
		try {
			DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
			this.configuration = dBuilder.parse(new File(fileName));
			configuration.getDocumentElement().normalize();
			subscriptions = new ArrayList<SubscriptionBean>();
			parseXmlConfig();
		} catch (IOException e) {
			logger.log(Level.SEVERE, "Cannot open config file:{0}", fileName);
			throw e;
		} catch (SAXException e) {
			logger.log(Level.SEVERE, "Cannot parse config file:"+fileName, e);
		} catch (ParserConfigurationException e) {
			logger.log(Level.SEVERE, "Cannot parse config file:"+fileName, e);
		}
	}


	/**
	 * Parse recherche.xml config file
	 * @param xmlFile
	 */
	protected void parseXmlConfig(){

		logger.log(Level.INFO, "Root element :{0}", configuration.getDocumentElement().getNodeName());
		NodeList subscriptionNodes = configuration.getDocumentElement().getElementsByTagName("subscription");
		for (int i = 0; i < subscriptionNodes.getLength(); i++) {

			Element subscription = (Element) subscriptionNodes.item(i);
			SubscriptionBean subscriptionBean = new SubscriptionBean();

			subscriptionBean.setName(subscription.getElementsByTagName("name").item(0).getTextContent());
			
			NodeList adressList = subscription.getElementsByTagName("emailAdress");
			for (int j = 0; j < adressList.getLength(); j++) {
				subscriptionBean.getEmailAdresses().add(adressList.item(j).getTextContent());
			}
			
			NodeList itemNodeList = subscription.getElementsByTagName("searchItem");
			for (int j = 0; j < itemNodeList.getLength(); j++) {
				
				Element itemElement = (Element) itemNodeList.item(j);
				
				SearchItemBean searchItemBean = new SearchItemBean();
				subscriptionBean.getSearchItems().add(searchItemBean);
				
				if (itemElement.getElementsByTagName("searchCategory").getLength() > 0) {
					searchItemBean.setSearchCategory(itemElement.getElementsByTagName("searchCategory").item(0).getTextContent());
				}
				searchItemBean.setSearchText(itemElement.getElementsByTagName("searchText").item(0).getTextContent());

				NodeList priceMinList = itemElement.getElementsByTagName("priceMin");
				if (priceMinList.getLength() > 0) {
					searchItemBean.setPriceMin(Integer.parseInt(priceMinList.item(0).getTextContent()));
				}
				NodeList priceMaxList = itemElement.getElementsByTagName("priceMax");
				if (priceMaxList.getLength() > 0) {
					searchItemBean.setPriceMax(Integer.parseInt(priceMaxList.item(0).getTextContent()));
				}
				
				NodeList checkOptionList = itemElement.getElementsByTagName("checkoption");
				if (checkOptionList.getLength() > 0) {
					for (int k = 0; k < checkOptionList.getLength(); k++){
						Element checkOptionElement = (Element) checkOptionList.item(k);
						searchItemBean.getCheckBoxList().add(checkOptionElement.getAttribute("id"));
					}
				}				
				
				NodeList locationList = itemElement.getElementsByTagName("location");
				if (locationList.getLength() > 0) {
					Element locationElement = (Element) locationList.item(0);
					String locationType = locationElement.getAttribute("type");
					if (locationType.equals(SearchItemBean.LocationType.FRANCE.name())){
						searchItemBean.setSearchLocation(SearchItemBean.LocationType.FRANCE);
					} else if (locationType.equals(SearchItemBean.LocationType.AUVERGNE.name())){
						searchItemBean.setSearchLocation(SearchItemBean.LocationType.AUVERGNE);
					} else if (locationType.equals(SearchItemBean.LocationType.PUY_DE_DOME.name())){
						searchItemBean.setSearchLocation(SearchItemBean.LocationType.PUY_DE_DOME);
					} else if (locationType.equals(SearchItemBean.LocationType.DEP_VOISINS.name())){
						searchItemBean.setSearchLocation(SearchItemBean.LocationType.DEP_VOISINS);
					} else if (locationType.equals(SearchItemBean.LocationType.LISTE_CP.name())){
						searchItemBean.setSearchLocation(SearchItemBean.LocationType.LISTE_CP);
						NodeList zipCodeList = locationElement.getElementsByTagName("zipCode");
						for (int k = 0; k < zipCodeList.getLength(); k++){
							Element zipCodeElement = (Element) zipCodeList.item(k);
							searchItemBean.getZipCodes().add(zipCodeElement.getTextContent());
						}
					}				
				}			
			}
			subscriptions.add(subscriptionBean);
		}
	}


	public Document getConfiguration() {
		return configuration;
	}


	public void setConfiguration(Document configuration) {
		this.configuration = configuration;
	}


	public List<SubscriptionBean> getSubscriptions() {
		return subscriptions;
	}


	public void setSubscriptions(List<SubscriptionBean> subscriptions) {
		this.subscriptions = subscriptions;
	}
	
	
}
